﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;


namespace AoYing_DeviceCollection
{
    public class HttpHelper
    {
        /// <summary>
        /// Http Post
        /// </summary>
        /// <param name="uri">资源地址</param>
        /// <param name="body"></param>
        /// <returns></returns>
        public static string HttpPost(string uri, string body)
        {

            BaseUtils._eventMsg.Info = $"uri【{uri}】body【{body}】";
            Encoding encoding = Encoding.UTF8;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            request.Method = "POST";
            request.Accept = "text/html, application/xhtml+xml, */*";
            request.ContentType = "application/json";

            if (!string.IsNullOrEmpty(body))
            {
                byte[] buffer = encoding.GetBytes(body);
                request.ContentLength = buffer.Length;
                request.GetRequestStream().Write(buffer, 0, buffer.Length);
            }
            else
            {
                request.ContentLength = 0;
            }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                return reader.ReadToEnd();
            }
        }

        public static async Task<string> HttpPostAsync(string uri, string body)
        {
            try
            {
                BaseUtils._eventMsg.Info = $"uri【{uri}】body【{body}】";

                Encoding encoding = Encoding.UTF8;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
                request.Method = "POST";
                request.Accept = "text/html, application/xhtml+xml, */*";
                request.ContentType = "application/json";

                // 异步写入请求体
                if (!string.IsNullOrEmpty(body))
                {
                    byte[] buffer = encoding.GetBytes(body);
                    request.ContentLength = buffer.Length;

                    using (Stream requestStream = await request.GetRequestStreamAsync())
                    {
                        await requestStream.WriteAsync(buffer, 0, buffer.Length);
                    }
                }
                else
                {
                    request.ContentLength = 0;
                }

                // 异步获取响应
                using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
                using (Stream responseStream = response.GetResponseStream())
                using (StreamReader reader = new StreamReader(responseStream, Encoding.UTF8))
                {
                    return await reader.ReadToEndAsync();
                }
            }
            catch (WebException ex)
            {
                // 处理HTTP错误响应
                if (ex.Response is HttpWebResponse errorResponse)
                {
                    using (Stream errorStream = errorResponse.GetResponseStream())
                    using (StreamReader reader = new StreamReader(errorStream, Encoding.UTF8))
                    {
                        string errorContent = await reader.ReadToEndAsync();
                        throw new HttpRequestException($"HTTP Error {(int)errorResponse.StatusCode}: {errorContent}", ex);
                    }
                }
                throw;
            }
            catch (Exception ex)
            {
                BaseUtils._eventMsg.ErrorMsg = $"HTTP请求失败: {ex.Message}";
                throw;
            }
        }
    }
}
